package com.apache.portal.contorller;

import com.apache.portal.common.vo.ProgressSingleton;
import com.apache.tools.StrUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description:  用于实时读取上传文件进度
 * 参考： https://blog.csdn.net/dcrose/article/details/79563969
 * @author fpchang 创建时间：2018-10-9
 */
public class ProgressServlet extends BaseHttpServlet {
    @Override
    protected void doInvoke(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String sessionid = request.getSession().getId();
        String tempSessionId = request.getParameter("tempSessionId");
        //使用sessionid + 文件名生成文件号，与上传的文件保持一致
        sessionid = StrUtil.doNull(tempSessionId,sessionid);
        Object size = ProgressSingleton.get(sessionid + "_size");
        size = size == null ? 1 : size;
        Object progress = ProgressSingleton.get(sessionid + "_progress");
        progress = progress == null ? 0 : progress;
        JSONObject json = new JSONObject();
        json.put("size", size);
        json.put("progress", progress);
        this.outputJson(json.toString(), response);
    }

}
